package filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import biz.SystemBiz;
import entity.User;

@Controller
public class UserValidate implements Filter {

	@Autowired
	private SystemBiz systemBiz;
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletResponse res = (HttpServletResponse) response;
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession(false);
		boolean validate = false;
		if (session != null) {
			User u = (User) session.getAttribute("LoginUser");
			if (u != null) {
				validate = true;
			}else{
				session.removeAttribute("LoginUser");
			}
		}
		if (validate) {
			chain.doFilter(req, res);
		} else {
			PrintWriter out = res.getWriter();
			out.print("<script>top.location='" + req.getContextPath()+ "/index.jsp'</script>");
			out.print("<script>location.href='" + req.getContextPath()+ "/index.jsp'</script>");
			out.flush();
			out.close();
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
